<?php
die('temporarily disabled');

require_once('database.inc.php');
require_once('track.inc.php');
require_once('functions.inc.php');
require_once('ad.inc.php');
require_once('dropdowns.inc.php');

//if (date("N") == 3 || date("N") == 4) 
	die("The challenge suggester is very heavy on the database, so it has been disabled until a solution can be found.");

#die("The challenge suggester is not very useful while Hattrick is down, and it creates a heavy server load, so it has been temporarily disabled. If you still see this message after 14:00 and HT is already back up, please bother lhoek@science.uva.nl about it.");

$dbm = connect_db("dbm");
$debug = false;

$perpage = 25;

$n = 0;
$page = 0;
if (isset($_GET['n']) && is_numeric($_GET['n'])) {
	$n = $_GET['n'];
	$page = $perpage * $_GET['n'];
}

$teamid = "";
if (isset($_GET['teamid']) && is_numeric($_GET['teamid']) && $_GET['teamid'] > 0) {
	$teamid = $_GET['teamid'];
}

$webserver = "www.hattrick.org";
if (isset($_GET['server'])) $webserver = $_GET['server'];
if ($webserver === "") $webserver = "www.hattrick.org";

$homeoption = 0; //no preference
$homecondition = "1";
if (isset($_GET['place']) && is_numeric($_GET['place']) && $_GET['place'] != 0) {
	if ($_GET['place'] > 0) {
		$homeoption = 1;
		$homecondition = "themf.home = 1";
	} else {
		$homeoption = -1;
		$homecondition = "themf.home = 0";
	}
}
$federation = 0;
$fedcondition = "1";
$fedmembership = "";
if (isset($_GET['fed']) && is_numeric($_GET['fed']) && $_GET['fed'] != 0) {
	$federation = $_GET['fed'];
	$fedcondition = "them.userid = fed_members.userid AND allianceid = $federation";
	$fedmembership = ", fed_members";
}

$matchtype = "1"; //cup
if (isset($_GET['cuprules']) && is_numeric($_GET['cuprules']) && $_GET['cuprules'] == 0) $matchtype = 0;

$sort = 0;
$sortby = "them.lastlogindate DESC";
if (isset($_GET['sort']) && is_numeric($_GET['sort']) && $_GET['sort'] == 1) $sort = 1;
if ($sort > 0) $sortby = "l.activeusers ASC, them.lastlogindate DESC";

$maxusers = 1000000;
if (isset($_GET['maxusers']) && is_numeric($_GET['maxusers']) && $_GET['maxusers'] > 0) $maxusers = $_GET['maxusers'];
$minusers = 0;
if (isset($_GET['minusers']) && is_numeric($_GET['minusers']) && $_GET['minusers'] > 0) $minusers = $_GET['minusers'];
if ($maxusers < $minusers) {
	$maxusers = 1000000;
	$minusers = 0;
}

if ($debug) echo "<!-- debug is on -->";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Maptrick - Friendly Challenge Helper</title>
</head>
<body>

<style>
.home {
	background-color: #D0D0FF;
}

.away {
	background-color: #FFFFD0;
}
</style>

This tool will help you arrange a friendly with another Coolness Calculator user; it will only propose friendlies where both parties would gain a flag (i.e., one home and one away flag). This is determined with the data stored in the local database, and the most up-to-date teams are shown first, so the data on the first pages is probably most accurate. As long as you make sure that your own team is up to date, you will certainly get a flag.<br /><br />

The tool does not know which teams are still in the cup, already booked a friendly or have disabled challenges, so you will have to try to challenge the team to see if it was possible. If not, try some more teams from the 2nd page, etc.<br /><br />

<b>Step 1:</b> make sure your <a href="coolness.php<?php if ($teamid > 0) echo "?tid=$teamid"; ?>#submit">coolness</a> is up to date.<br /><br />
<b>Step 2:</b> Log in to Hattrick and note which server you are logged in to (e.g., www81.hattrick.org).<br /><br />
<b>Step 3:</b> Fill in and submit the form below:<br /><br />

<form method="GET">
<table>
<tr><td>Server<td>http://<td><input name="server" size="30" value="<?php echo $webserver; ?>"><td><?php if (isset($_GET['teamid']) && $webserver === "www.hattrick.org") echo "<b>&lt;--- <font color=\"red\">CHANGE THIS OR THE LINKS WON'T WORK!</font></b>"; ?>
<tr><td>Your TeamID<td><td><input name="teamid" size="20" value="<?php echo $teamid; ?>"><td>
<tr><td>Home or Away?<td><td><select name="place">
	<option value="0"<?php if ($homeoption == 0) echo " selected=\"selected\"";?>>Show both</option>
	<option value="-1"<?php if ($homeoption == -1) echo " selected=\"selected\"";?>>Only my home</option>
	<option value="1"<?php if ($homeoption == 1) echo " selected=\"selected\"";?>>Only away</option>
</select><td>
<?php if ($debug) { ?>
	<tr><td>Cup rules?<td><td><select name="cuprules">
		<option value="1"<?php if ($matchtype == 1) echo " selected=\"selected\"";?>>Yes please!</option>
		<option value="0"<?php if ($matchtype == 0) echo " selected=\"selected\"";?>>No thanks.</option>
	</select><td>
<?php } ?>
<tr><td>Sort by...<td><td><select name="sort">
	<option value="0"<?php if ($sort == 0) echo " selected=\"selected\"";?>>Last login</option>
	<option value="1"<?php if ($sort == 1) echo " selected=\"selected\"";?>>Coolness</option>
</select><td>
<tr><td>Minimum coolness?<td><td><select name="maxusers">
	<option>No minimum</option>
	<option></option>
<?php
$query = mysql_query("SELECT SUM(activeusers) grand_total FROM leagues_daily WHERE leagueid != 255", $dbm) or die(mysql_error());
$row = mysql_fetch_array($query);
$totalusers = $row['grand_total'];

$query = mysql_query("SELECT leagueid, leaguename, activeusers, ROUND($totalusers / activeusers,1) coolness FROM leagues_daily WHERE leagueid != 255 ORDER BY activeusers DESC", $dbm) or die(mysql_error());
$curmin = 1000000;
while ($row = mysql_fetch_array($query)) {
	if ($row['activeusers'] < $curmin) {
		$curmin = $row['activeusers'];
		echo "<option value=\"{$row['activeusers']}\"";
		if ($row['activeusers'] == $maxusers) echo " selected=\"selected\"";
		echo ">{$row['coolness']} ({$row['leaguename']}, {$row['activeusers']} users)</option>\n";
	}
}
?>
</select><td>
<tr><td>Maximum coolness?<td><td><select name="minusers">
	<option>No maximum</option>
	<option></option>
<?php
$query = mysql_query("SELECT leagueid, leaguename, activeusers, ROUND($totalusers / activeusers,1) coolness FROM leagues_daily WHERE leagueid != 255 ORDER BY activeusers ASC", $dbm) or die(mysql_error());
$curmax = 0;
while ($row = mysql_fetch_array($query)) {
	if ($row['activeusers'] > $curmax) {
		$curmax = $row['activeusers'];
		echo "<option value=\"{$row['activeusers']}\"";
		if ($row['activeusers'] == $minusers) echo " selected=\"selected\"";
		echo ">{$row['coolness']} ({$row['leaguename']}, {$row['activeusers']} users)</option>\n";
	}
}
?>
</select><td>
<tr><td>Limit to fed?<td><td><?php printgenericdropdown("fed", $federation, "No preference", getAsocArr("fed_details", "id", "name", $dbm, "LTRIM(name) ASC")); ?>
</table>
<input type="submit" value="Submit"><br />
</form>
<b>Step 4:</b> Click team names to open their team pages from where you can challenge them. Get <?php echo $perpage; ?> new suggestions by clicking "next" at the bottom of the page. Repeat until you have the maximum of 25 standing challenges. If the countries you are seeing are "not cool enough" or "too cool", try setting a Minimum or Maximum Coolness in the form above.<br /><br />

You can judge your chances of the team accepting your challenge by looking at the number of flags they have chased at the venue you are proposing, and the coolness of those flags. Consider that teams with 0 or a few flags may be new teams without a waiting list; on the other hands, teams with many flags are probably dedicated flag chasers who will be happy to get a new flag.<br />
Unfortunately, it is technically difficult to order the list by this column, but here too, you can just go to the next page to get a list of new suggestions.<br /><br />
<b>Step 5:</b> Wait for someone to accept your challenge. If you're <i>really</i> cool, this shouldn't take long ;)<br /><br />
<?php
display_ad("challenge_suggester");
?>
<br />
<?php if ($teamid > 0) {
	
	$query = mysql_query("SELECT SUM(activeusers) AS active FROM leagues_daily WHERE leagueid != 255", $dbm) or die (mysql_error());
	$row = mysql_fetch_array($query);
	$globalactive = $row['active'];

	$query = mysql_query("SELECT * FROM `flags_updated` WHERE teamid = $teamid", $dbm) or die (mysql_error());
	$row = mysql_fetch_array($query);
	echo "Challenge suggestions for team <b>{$row['TeamName']}</b> (last update: {$row['FetchedDate']}):<br /><br />\n";


	$hometext = array(
		0 => "Home",
		1 => "Away"
	);

	$leaguenames = getAsocArr("leagues_daily", "LeagueID", "LeagueName", $dbm);

	$querytext = 	"SELECT
			them.teamname, them.teamid, them.userid, them.leagueid, themf.home, them.lastlogindate, l.activeusers
			FROM flags_updated me, flags_updated them, flags_v2 mef, flags_v2 themf, leagues_daily l $fedmembership
			WHERE l.leagueid = them.leagueid
			AND l.activeusers <= $maxusers
			AND l.activeusers >= $minusers
			AND me.teamid = $teamid
			AND me.userid = mef.userid
			AND them.userid = themf.userid
			AND them.userid != me.userid
			AND mef.checked = 0
			AND themf.checked = 0
			AND me.leagueid = themf.leagueid
			AND them.leagueid = mef.leagueid
			AND mef.home != themf.home
			AND $homecondition
			AND $fedcondition
			ORDER BY $sortby
			LIMIT $page,$perpage";

	$query = mysql_query($querytext, $dbm) or die (mysql_error());
	$i = $n * $perpage;
	$lastid = 0;
	if(mysql_num_rows($query) > 0) {
	?>
<table>
<tr><th>#<th>League (users)<th>Team<th>Last (recorded) login<th>Place<th colspan="2">Their coolness / flags<?php if ($debug) echo "<th>DEBUG IS ON" ?>
<?php
		while ($row = mysql_fetch_array($query)) {
			$i++;
			if ($row['home'] == 0) {
				$locationclass = "away";
				$subquerytext = "SELECT ROUND( SUM( $globalactive / activeusers ) ) coolness, COUNT( DISTINCT flags.leagueid ) num
					FROM flags_v2 flags, leagues_daily
					WHERE flags.leagueid = leagues_daily.leagueid
					AND checked = 1
					AND home = 0
					AND userid = {$row['userid']}
					GROUP BY userid, home";
			} else {
				$locationclass = "home";
				$subquerytext = "SELECT ROUND( SUM( $globalactive / activeusers ) ) coolness, COUNT( DISTINCT flags.leagueid ) num
					FROM flags_v2 flags, leagues_daily
					WHERE flags.leagueid = leagues_daily.leagueid
					AND checked = 1
					AND home = 1
					AND userid = {$row['userid']}
					GROUP BY userid, home";
			}
			$subquery = mysql_query($subquerytext, $dbm) or die (mysql_error());
			if (mysql_num_rows($subquery) > 0) {
				$subrow = mysql_fetch_array($subquery);
			} else {
				$subrow = array(
					'coolness' => 0,
					'num' => 0	
				);
			}
			echo "<tr class=\"$locationclass\"><td>";
			if ($lastid != $row['teamid']) echo $i;
			echo "<td><img src=\"flags/{$row['leagueid']}flag.gif\" border=\"1\"> {$leaguenames[$row['leagueid']]} ({$row['activeusers']})<td><a href=\"http://$webserver/common/teamDetails.asp?teamID={$row['teamid']}\">{$row['teamname']}</a><td>{$row['lastlogindate']}<td>{$hometext[$row['home']]}<td align=\"right\"><a href=\"coolness.php?tid={$row['teamid']}\">{$subrow['coolness']}</a><td align=\"right\"><a href=\"coolness.php?tid={$row['teamid']}\">{$subrow['num']}</a>";
			if ($debug) echo "<td><a href=\"http://$webserver/Common/challanges.asp?actionType=challange&matchType=$matchtype&matchPlace={$row['home']}&opponentID={$row['teamid']}\">Challenge</a>\n";
			$lastid = $row['teamid'];
		}

		?>
</table>
		<?php
		if ($n > 0) echo "<a href=\"challenge_suggester.php?server=$webserver&teamid=$teamid&place=$homeoption&cuprules=$matchtype&sort=$sort&maxusers=$maxusers&minusers=$minusers&n=" . ($n-1) . "\">previous</a> | ";
		else echo "previous | ";
		if (mysql_num_rows($query) == $perpage) echo "<a href=\"challenge_suggester.php?server=$webserver&teamid=$teamid&place=$homeoption&cuprules=$matchtype&sort=$sort&maxusers=$maxusers&minusers=$minusers&n=" . ($n+1) . "\">next</a>\n";
		else echo "next";
		echo "<br />\n";
	} else {
		echo "No teams could be found that satisfy your criteria! Try relaxing the constraints a little.<br/><br/>\n";
	}
}
urchin();
?>
</body>
</html>
